package com.petsdar.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.petsdar.service.PowerServiceImpl;
import com.petsdar.utils.Constant;
import com.petsdar.utils.JedisUtil;
import com.petsdar.utils.JsonUtil;
import com.petsdar.utils.ResultUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * User: heroC
 * Date: 2020/6/27
 * Time: 16:36
 * Description: 登录拦截，权限获取
 * Version: V1.0
 */
public class PetsDarInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper = new ObjectMapper();
    private HashMap<String, Boolean> powerMap = new HashMap<>();
    boolean status = false;
    private String userName;
    private String result;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        /**
         * 拦截以/check结尾的接口，该接口为登录验证接口，
         * 主要是对其进行登录验证，通过验证passID是否在缓存
         * 存在，根据用户名从缓存中获取权限。返回对应的json
         * 响应结果。响应结果被返回，该接口被拦截，不放行。
         * 因为该接口已经在此处处理完成。
         */
        if (url.endsWith("/check")){
            String info = "";
            String line = "";
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null){
                info+=line;
            }
            Map mapInfo = objectMapper.readValue(info, Map.class);
            String passID = (String) mapInfo.get(Constant.PASS_ID);
            status = JedisUtil.isKey(passID,0);
            PrintWriter out = response.getWriter();
            if (status){
                String userInfo = JedisUtil.getValue(passID, 0);
                Map userMap = JsonUtil.toObject(userInfo, Map.class, PetsDarInterceptor.class);
                userName = (String) userMap.get("userName");
                if (userName.contains(Constant.KEEPER_POWER_ID)){
                    result = ResultUtil.success(getPower(true));
                    out.append(result);
                }else {
                    result = ResultUtil.success(getPower(false));
                    out.append(result);
                }
            }else {
                result = ResultUtil.fail();
                out.append(result);
            }
            return false;
        }

        /**
         * 拦截以/account-info结尾的接口，从缓存中获取权限数据，并将其返回。
         */
        if (url.endsWith("/account-info")){
            String info = "";
            String line = "";
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null){
                info+=line;
            }
            Map map = objectMapper.readValue(info, Map.class);
            String passID = (String) map.get(Constant.PASS_ID);
            status = JedisUtil.isKey(passID,0);
            PrintWriter out = response.getWriter();
            if (status){
                String value = JedisUtil.getValue(passID, 0);
                out.append(ResultUtil.success(value));
            }else {
                out.append(ResultUtil.fail());
            }
            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 从缓存中获取权限信息,并返回存储处理后的权限的map对象
     * @param type true表示是店长账户，false表示是admin账户
     * @return
     */
    private Map<String,Boolean> getPower(boolean type){
        powerMap.clear();
        if (type){
            String empValue = JedisUtil.getValue(Constant.PR_EMP_POWER, 1);
            String shopValue = JedisUtil.getValue(Constant.PR_SHOP_POWER, 1);
            boolean[] empPower = JsonUtil.toObject(empValue, boolean[].class, PetsDarInterceptor.class);
            boolean[] shopPower = JsonUtil.toObject(shopValue, boolean[].class, PetsDarInterceptor.class);
            if (empPower.length > 0 && shopPower.length > 0){
                powerMap.put(Constant.IS_SHOW_ADD,empPower[0]);
                powerMap.put(Constant.IS_SHOW_DEL,empPower[1]);
                powerMap.put(Constant.IS_SHOW_EDIT,empPower[2]);
                powerMap.put(Constant.IS_SHOW_AREA,empPower[3]);
                powerMap.put(Constant.IS_SHOP_ADD,false);
                powerMap.put(Constant.IS_SHOP_EDIT,shopPower[0]);
                powerMap.put(Constant.IS_SHOP_DEL,false);
                powerMap.put(Constant.IS_POWER_SHOW,false);
                powerMap.put(Constant.IS_POSITION_ADD,false);
                powerMap.put(Constant.IS_POSITION_DEL,false);
                powerMap.put(Constant.IS_POSITION_EDIT,false);
                return powerMap;
            }
        }else {
            powerMap.put(Constant.IS_SHOW_ADD,true);
            powerMap.put(Constant.IS_SHOW_DEL,true);
            powerMap.put(Constant.IS_SHOW_EDIT,true);
            powerMap.put(Constant.IS_SHOW_AREA,true);
            powerMap.put(Constant.IS_SHOP_ADD,true);
            powerMap.put(Constant.IS_SHOP_EDIT,true);
            powerMap.put(Constant.IS_SHOP_DEL,true);
            powerMap.put(Constant.IS_POWER_SHOW,true);
            powerMap.put(Constant.IS_POSITION_ADD,true);
            powerMap.put(Constant.IS_POSITION_DEL,true);
            powerMap.put(Constant.IS_POSITION_EDIT,true);
        }
        return powerMap;
    }
}
